package com.kanshu.ksgb.fastread.doudou.common.util;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;


public class FileUtils {
    private static final String[] filters = {".txt"/*, ".pdf", ".epub"*/};

    public static File[] read(File file) {
        if (file.isDirectory()) {// 是文件夹
            File[] files = file.listFiles(new FileFilter() {// 设置过滤条件

                public boolean accept(File pathname) {
                    if (pathname.isDirectory()) {// 是文件夹，true不过滤
                        return true;
                    }
                    boolean flag = false;
                    if (pathname.isFile()) {
                        String fileName = pathname.getName().toLowerCase();
                        for (int i = 0; i < filters.length; i++) {
                            if (fileName.endsWith(filters[i])) {
                                flag = true;
                                break;
                            }
                        }
                    }
                    return flag;
                }
            });

            return files;
        }
        return null;
    }

    public static String readString(File file, int begin, int size) {
        try {
            DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
            Log.d("MyBook", "文件总长度：" + file.length());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            // 从什么位置开始读
            dataInputStream.skip(begin);
            // 读多少数据
            byte[] b = new byte[size];
            int i = -1;
            if ((i = dataInputStream.read(b, 0, b.length)) != -1) {
                out.write(b, 0, i);
                // randomAccessFile.skipBytes(1024);
                String string = out.toString("UTF-8");
                Log.d("MyBook", "begin：" + begin);
                Log.d("MyBook", "size：" + size);
                // Log.d("MyBook", "读取的文本：" + string);
                return string;
            }
            out.close();
            dataInputStream.close();
        } catch (Exception e) {
            Log.d("MyBook", e.getMessage());
        }
        return null;
    }

    /**
     * 获取缓存路径
     *
     * @param context
     * @return
     */
    public static File getCacheDir(Context context) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            if (context.getExternalCacheDir() == null) {
                if (context.getCacheDir() != null) {
                    cachePath = context.getCacheDir().getPath();
                } else {
                    cachePath = Environment.getExternalStorageDirectory().getPath();
                }
            } else {
                cachePath = context.getExternalCacheDir().getPath();
            }

        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath);
    }

    /**
     * 格式化大小
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }
        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    /**
     * 获取文件夹内所有文件大小的和
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            if (fileList == null) {
                return 0;
            }
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 获取文件夹内所有下载文件大小的和
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getDownloadSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            if (fileList == null) {
                return 0;
            }
            for (File aFileList : fileList) {
                if (aFileList.getPath().endsWith("download.txt")) {
                    size += aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除文件夹内的文件
     *
     * @param filePath
     * @param deleteThisPath
     * @return
     */
    public static boolean deleteFolderFile(String filePath, boolean deleteThisPath) {
        try {
            File file = new File(filePath);
            if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (File file1 : files) {
                    deleteFolderFile(file1.getAbsolutePath(), true);
                }
            }
            if (deleteThisPath) {
                if (!file.isDirectory()) {
                    file.delete();
                } else {
                    if (file.listFiles().length == 0) {
                        file.delete();
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建文件目录
     *
     * @param dirPath
     * @return
     */
    public static String createDir(String dirPath) {
        try {
            File file = new File(dirPath);
            if (file.getParentFile().exists()) {
                file.mkdir();
                return file.getAbsolutePath();
            } else {
                createDir(file.getParentFile().getAbsolutePath());
                file.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath;
    }

    /**
     * 创建文件
     *
     * @param file
     * @return
     */
    public static String createFile(File file) {
        try {
            if (file.getParentFile().exists()) {
                file.createNewFile();
                return file.getAbsolutePath();
            } else {
                createDir(file.getParentFile().getAbsolutePath());
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getPatchFile() {
        File file = new File(getPatchFilePath());
        try {
            if (file.exists())
                file.delete();
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getPath();
    }

    /**
     * 创建根缓存目录
     *
     * @param context
     * @return
     */
    public static String createRootPath(Context context) {
        String cacheRootPath = "";
        if (isSdCardAvailable()) {
            // /sdcard/Android/data/<application package>/cache
            try {
                if (context.getExternalCacheDir() != null) {
                    cacheRootPath = context.getExternalCacheDir().getPath();
                }
            } catch (Exception e) {
                if (context.getCacheDir() != null) {
                    cacheRootPath = context.getCacheDir().getPath();
                }
            }

        } else {
            // /data/data/<application package>/cache
            if (context.getCacheDir() != null) {
                cacheRootPath = context.getCacheDir().getPath();
            }
        }
        if (TextUtils.isEmpty(cacheRootPath)) {
            File file = new File(Environment.getExternalStorageDirectory(), "reader_cache");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            cacheRootPath = file.getPath();
        }
        return cacheRootPath;
    }

    public static String getCharset(String fileName) {
        BufferedInputStream bis = null;
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            bis = new BufferedInputStream(new FileInputStream(fileName));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE
                    && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF
                    && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            }
            bis.mark(0);
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的，也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
                            // (0x80 - 0xBF),也可能在GB编码内
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错，但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return charset;
    }




    /**
     * 将内容写入文件
     *
     * @param filePath eg:/mnt/sdcard/demo.txt
     * @param content  内容
     * @param isAppend 是否追加
     */
    public static void writeFile(String filePath, String content, boolean isAppend) {
        try {
            FileOutputStream fout = new FileOutputStream(filePath, isAppend);
            byte[] bytes = content.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getPatchFilePath() {
        return getCacheDir(Xutils.getContext()).getPath() + "/ps7z";
    }

    /**
     * 获取剩余可用空间
     * @return
     */
    public static String getReadSystem() {
        //获取SD卡可用剩余空间
        long SDFreeSpace = Environment.getExternalStorageDirectory().getFreeSpace();
        return getFormatSize(SDFreeSpace);
    }

    public static boolean isSdCardAvailable() {
        try {
            // 部分手机存在调用系统的方法出现空指正
            String var0;
            return (var0 = Environment.getExternalStorageState()) != null && var0.length() > 0 && (var0.equals("mounted") || var0.equals("mounted_ro")) && Environment.getExternalStorageDirectory() != null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

}
